﻿using DriverLicence.Cnsl.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace DriverLicence.Cnsl.XmlLoader
{
    public class XmlQuizManager
    {
        private static XmlQuizManager _instance;

        private XmlQuizManager()
        { }

        public static XmlQuizManager GetInstance()
        {
            if(_instance == null)
            {
                _instance = new XmlQuizManager();
            }
            return _instance;
        }

        public Quiz Load()
        {
            XDocument xdocument = XDocument.Load("XmlConfiguration/DriverLicenceQuiz.xml");
            return new Quiz
            {
                Title = xdocument.Descendants("title").First().Value,
                Questions = LoadQuestions(xdocument)
            };
        }

        private Question[] LoadQuestions(XDocument xdocument)
        {
            List<Question> result = new List<Question>();
            xdocument.Descendants("question").ToList().ForEach(q => result.Add(LoadQuestion(q)));
            return result.ToArray();
        }

        private Question LoadQuestion(XElement questionNodeElement)
        {
            return new Question
            {
                Statement = questionNodeElement.Descendants("statement").First().Value.Trim(),
                Options = LoadQuestionOption(questionNodeElement)
            };
        }

        private IAnswer[] LoadQuestionOption(XElement questionNodeElement)
        {
            List<IAnswer> result = new List<IAnswer>();
            var options = questionNodeElement.Descendants("options").Descendants();
            result.Add(LoadRightAnswer(options));
            result.AddRange(LoadWrongAnswers(options));
            return result.ToArray();
        }

        private IEnumerable<IAnswer> LoadWrongAnswers(IEnumerable<XElement> options)
        {
            List<IAnswer> result = new List<IAnswer>();
            foreach (var w in options.Where(x => x.Name.LocalName == "wrong"))
            {
                result.Add(new WrongAnswer() { Value = w.Value.Trim() });
            }
            return result;
        }

        private IAnswer LoadRightAnswer(IEnumerable<XElement> optionsNodes)
        {
            return new RightAnswer() { Value = optionsNodes.First(x => x.Name.LocalName == "right").Value.Trim() };
        }
    }
}
